package cn.tom.controller.adm;

import cn.tom.tools.XResp;
import cn.tom.entity.Hot;
import cn.tom.tools.XJson;
import cn.tom.service.HotService;
import cn.tom.service.LargeFileService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/api/adm/hot")
public class AdmHotController {
    @Resource
    private HotService hotService;
    @Resource
    private LargeFileService largeFileService;


    @GetMapping("/remove/{id}")
    public XJson delete(@PathVariable int id){
        int del = hotService.del(id);
        if(del == 0) return XResp.pack(501,"删除失败",null);
        return XResp.pack(200,"删除成功",hotService.findAll());
    }

    @GetMapping("/findById/{id}")
    public XJson findById(@PathVariable int id){
        Hot hot = hotService.findById(id);
        return XResp.pack(200,"ok",hot);
    }


    @GetMapping("/findAll")
    public XJson findAll(Integer type){
        List<Hot> list = hotService.findAll();
        return XResp.pack(200,"ok",list);
    }

    @PostMapping("/addUp")
    public XJson addHOt(@RequestParam(value = "pic" , required = false)
                        MultipartFile file , Hot hot)
            throws IOException {
        if(hot.getId() > 0){
            if(file != null && file.getSize() > 0){
                largeFileService.delete(hot.getPicture());
                byte[] bytes = file.getBytes();
                String fileName = file.getOriginalFilename();
                largeFileService.add(hot.getPicture(),fileName,bytes);
            }
            int update = hotService.update(hot);
            Hot byId = hotService.findById(hot.getId());
            if(update == 0) return XResp.pack(501,"修改失败","");
            return XResp.pack(200,"修改成功",byId);
        }
        //有图片直接添加 图片表
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-","");
        if(file != null && file.getSize() > 0){
            byte[] bytes = file.getBytes();
            String fileName = file.getOriginalFilename();
            largeFileService.add(uuid,fileName,bytes);
        }
        hot.setPicture(uuid);
        //--------------------------------------------------------------------------------
        //添加
        int add = hotService.add(hot);
        Hot byId = hotService.findById(hot.getId());
        System.out.println(hot.getId());
        if(add == 0)return XResp.pack(501,"添加失败","");
        return XResp.pack(200,"添加成功",byId);
    }
}
